<?php

class FacturasController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column2';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
			'postOnly + delete', // we only allow deletion via POST request
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','view',  'adminc', 'adminp','datoc', 'datoc2','datop','pdf'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete', 'adminc', 'datoc', 'datoc2', 'datop', 'admin1', 'pdf', 'view', 'pdfl'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model = new Facturas;
		if(isset($_POST['Facturas']))
		{
			
			$model->attributes=$_POST['Facturas'];
			if($model->TIPO==1)
			{
				$max = Yii::app()->db->createCommand()->select('max(IDFACTURA) as max')->from('facturas')->queryScalar();
				$ind = Yii::app()->db->createCommand()->select('max(dfactura) as max')->from('indices')->queryScalar();

				if($max!=null && $max>=$ind){
					$max=$max+1;
					$max="00000000$max";
					$tam = strlen($max);
					$max= substr($max, ($tam-7),$tam);
					$model->IDFACTURA=($max);
				}
				else{
					if($max<$ind)
					{
						$max=$ind;
						$max="00000000$max";
						$tam = strlen($max);
						$max= substr($max, ($tam-7),$tam);
						$model->IDFACTURA=($max);
					}
					else{$model->IDFACTURA='0000000';}
				}
				date_default_timezone_set("America/Costa_Rica"); 
				$model->FECHA=date('Y-m-d H:i:s');
				$model->IDCL=$_POST['ID'];

				//transaccion
				$transaction=$model->dbConnection->beginTransaction();
				try{


					if($model->save()){
						//llenado de detalle
	   	     		$cont=1;
					$line=1;
					$cer=0;
					while($cont<=$_POST['cant_campos'])
					{
						if(isset($_POST['hdnCodigo_'.$cont]))
						{
							$model1 = new Detfactura;
			  	     		$model1->IDFACTURA=$model->IDFACTURA;
							$model1->IDINVENTARIO =$_POST['hdnCodigo_'.$cont];
							$model1->CANTIDAD = $_POST["hdnCant_".$cont];
							$model1->PRECIO = $_POST["hdnPrecio_".$cont];
							$model1->DESCUENTO = $_POST["hdnDescuento_".$cont];
							$model1->IMPUESTO = $_POST["hdnImpuesto_".$cont];
							$model1->IDDETALLE= $line;
							$line++;

							$inventario=$this->loadModelInventario($_POST['hdnCodigo_'.$cont]);
							$inventario->CANTIDAD = ((int) $inventario->CANTIDAD - (int) $_POST["hdnCant_".$cont]);
							
							if(!$model1->save())
							{
								$cont=$_POST['cant_campos'];
								Yii::app()->user->setFlash('Error','En este momento no se puede realizar la factura, vuelva a intentar o contacte al administrador');
								$line=1;
							}
							if(!$inventario->save())
							{
								$cont=$_POST['cant_campos'];
								Yii::app()->user->setFlash('Error','Error al crear la factura');
								$line=1;
							}
						}
						$cont++;
						
					}
					if($line>1)
					{
						$sql = "Insert into bitacora (IDUSUARIO, Accion, Descripcion, Fecha) Values('".Yii::app()->user->id."','1','Alta de Factura $model->IDFACTURA','$model->FECHA')";
						$connection = Yii::app() -> db;
						$command = $connection -> createCommand($sql);
						$command -> execute();
						$transaction->commit();
						$this->redirect(array('view','id'=>$model->IDFACTURA));
						Yii::app()->user->setFlash('Error','demo'.$inventario->CANTIDAD);
					}
					else{
						Yii::app()->user->setFlash('Error','Error al crear factura');
						$transaction->rollBack();
					}
					}

				}
				catch(Exception $e){
					Yii::app()->user->setFlash('Error','Error al crear factura');
	    			$transaction->rollBack();
				}
		}//fin factura e inicia proforma
		else{
			$max = Yii::app()->db->createCommand()->select('max(IDFACTURA) as max')->from('facturas')->queryScalar();
			if($max!=null){
				$max=$max+1;
				$max="00000000$max";
				$tam = strlen($max);
				$max= substr($max, ($tam-7),$tam);
				$model->IDFACTURA=($max);
			}
			else{$model->IDFACTURA='0000000';}
			date_default_timezone_set("America/Costa_Rica"); 
			$model->FECHA=date('Y-m-d H:i:s');
			$model->IDCL=$_POST['ID'];
			$model->TIPO=2;

			//transaccion
			$transaction=$model->dbConnection->beginTransaction();
			try{


				if($model->save()){
					//llenado de detalle
   	     		$cont=1;
				$line=1;
				$cer=0;
				while($cont<=$_POST['cant_campos'])
				{
					if(isset($_POST['hdnCodigo_'.$cont]))
					{
						$model1 = new Detfactura;
		  	     		$model1->IDFACTURA=$model->IDFACTURA;
						$model1->IDINVENTARIO =$_POST['hdnCodigo_'.$cont];
						$model1->CANTIDAD = $_POST["hdnCant_".$cont];
						$model1->PRECIO = $_POST["hdnPrecio_".$cont];
						$model1->DESCUENTO = '0';
						$model1->IMPUESTO = $_POST["hdnImpuesto_".$cont];
						$model1->IDDETALLE= $line;
						$line++;

						if(!$model1->save())
						{
							Yii::app()->user->setFlash('Error','Error al crear factura');
							$cont=$_POST['cant_campos'];
							$cer=1;
						}
					}
					$cont++;
					
				}
				if($cer==0 && $line>1)
				{
					$sql = "Insert into bitacora (IDUSUARIO, Accion, Descripcion, Fecha) Values('".Yii::app()->user->id."','1','Alta de Factura Proforma $model->IDFACTURA','$model->FECHA')";
					$connection = Yii::app() -> db;
					$command = $connection -> createCommand($sql);
					$command -> execute();
					$transaction->commit();
					$this->redirect(array('view','id'=>$model->IDFACTURA));
				}
				else{
					Yii::app()->user->setFlash('Error','Error al crear factura');
					$transaction->rollBack();
				}
				}

			}
			catch(Exception $e){
				Yii::app()->user->setFlash('Error','Error al crear factura'.$e);
    			$transaction->rollBack();
			}
		}
	}
		$this->render('create',array(
			'model'=>$model,
		));
}


	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Facturas('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Facturas']))
			$model->attributes=$_GET['Facturas'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}
	public function actionAdminc()
	{
		
		$model=new Clientes('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Clientes']))
			$model->attributes=$_GET['Clientes'];

		$this->render('Admincliente',array(
			'model'=>$model,
		));
	}

	public function actionAdminp()
	{
		$model=new Inventario('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Inventario']))
			$model->attributes=$_GET['Inventario'];
       

		$this->render('Adminproducto',array(
			'model'=>$model,
		));
	}

	//popup cliente
	public function actionDatoc($id){
		//se valida el estado que sea activo y el id
		if($model=Clientes::model()->find('ID =:id AND ESTADO=:estado',
	array(
  		':id'=>$id,
  		':estado'=>'1',
	)))
		{

		$res = array(
			'ID'=>$model->ID,
			'IDCL'=>$model->IDCL,
			'NOMBRE'=>$model->NOMBRE,
			'APELLIDO'=>$model->APELLIDO,
			);

		echo CJSON::encode($res);
		}
		else
		{
			$res = array(
			'IDCL'=>"1",
			);

		echo CJSON::encode($res);
		}
	}

		//digitacion de cedula cliente
	public function actionDatoc2($cod){
		//se valida el estado que sea activo y el id
		if($model=Clientes::model()->find('IDCL=:cod AND ESTADO=:estado',
	array(
  		':cod'=>$cod,
  		':estado'=>'1',
	)))
		{
		$res = array(
			'ID'=>$model->ID,
			'IDCL'=>$model->IDCL,
			'NOMBRE'=>$model->NOMBRE,
			'APELLIDO'=>$model->APELLIDO,
			);

		echo CJSON::encode($res);
		}
		else
		{
			$res = array(
			'IDCL'=>"1",
			'ID'=>$cod,
			);

		echo CJSON::encode($res);
		}
	}

	//popup proveedor
	public function actionDatop($id){
		if($model=Inventario::model()->find('IDINVENTARIO=:id AND ESTADO=:estado',
	array(
  		':id'=>$id,
  		':estado'=>'1',
	)))
		{
		$res = array(
			'ID'=>$model->IDINVENTARIO,
			'Descripcion'=>$model->DESCRIPCION,
			'Cant'=>$model->CANTIDAD,
			'Pre'=>$model->PRECIO,
			'Precio'=> $model->PRECIOV,
			'Imp'=> $model->IMPUESTO,
			);

		echo CJSON::encode($res);
		}
		else{
			$res = array(
			'ID'=>"",
			'Descripcion'=>"",
			'Cant'=>"0",
			'Precio'=>"0",
			'Imp'=>"0",
			);

		echo CJSON::encode($res);
		}
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Facturas the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=Facturas::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
	
		return $model;
	}
	
//Busqueda para actualizar el inventario
	public function loadModelInventario($id)
	{
		$model=Inventario::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Facturas $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='facturasform')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

//Crear factura en pdf
	public function actionPdf($id)
    {
        $this->renderpartial('pdf',array(
            'model'=>$this->loadModel($id)
        ));
    }
	//Lista de de facturas en pdf
	public function actionPdfL()
    {
    	$dataProvider = $_SESSION['datos']->getData();
    	$dataProvider2 = $_SESSION['datos']->getData();

        $this->renderpartial('pdfl', array("dataProvider"=>$dataProvider, "dataProvider2"=> $dataProvider2));
    }
//cargar detalle
    public function loadModel2($id)
	{
		$model=Detfactura::model()->find('IDFACTURA = '.$id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

}
